import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:flutter_huawei_cloud/flutter_huawei_cloud.dart';
import 'package:image_picker/image_picker.dart';
import 'package:uuid/uuid.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _filePath = '';
  final _picker = ImagePicker();
  final _flutterHuaweiCloudPlugin = FlutterHuaweiCloud();

  StreamSubscription? _subscription;

  @override
  void initState() {
    super.initState();
    initPlatformState();
  }

  @override
  void dispose() {
    _subscription?.cancel();
    super.dispose();
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    // String platformVersion;
    // // Platform messages may fail, so we use a try/catch PlatformException.
    // // We also handle the message potentially returning null.
    // try {
    //   platformVersion =
    //       await _flutterHuaweiCloudPlugin.getPlatformVersion() ??
    //       'Unknown platform version';
    // } on PlatformException {
    //   platformVersion = 'Failed to get platform version.';
    // }

    // // If the widget was removed from the tree while the asynchronous platform
    // // message was in flight, we want to discard the reply rather than calling
    // // setState to update our non-existent appearance.
    // if (!mounted) return;
    try {
      _subscription = _flutterHuaweiCloudPlugin.onUploadProgress.listen((
        onData,
      ) {
        print("上传进度：${onData.progress}");
      });
      _flutterHuaweiCloudPlugin.initialize(
        accessKey: "JDSG6OSLCUGQVGSD2CGY",
        secretKey: "v0vYnhWcwKemvw8OR5ZDEa5hjmBYFHJuKFo8PNYs",
        region: "cn-east-3",
      );
    } catch (e) {
      print("HuaweiCloud Initialize Error: $e");
    }
  }

  Future<void> pickSingleImage() async {
    try {
      XFile? file = await _picker.pickImage(source: ImageSource.gallery);
      print("File: ${file?.path}");
      _filePath = file?.path ?? '';
      setState(() {});
      if (file != null) {
        uploadImage(file.path);
      }
    } catch (e) {
      print("Pick Single Image Error");
    }
  }

  Future<void> pickMultipleImage() async {
    try {
      List<XFile> files = await _picker.pickMultiImage(limit: 9);
      uploadMultipleImage(files);
    } catch (e) {
      print("Pick Multiple Image Error");
    }
  }

  Future<void> uploadImage(String filePath) async {
    try {
      DateTime now = DateTime.now();
      String uuid = Uuid().v4();
      String objectKey =
          "picture/${now.year}/${now.month}/${now.day}/$uuid${now.millisecondsSinceEpoch}.jpg";
      String? res = await _flutterHuaweiCloudPlugin.uploadFile(
        "future-mural",
        objectKey,
        filePath,
      );
      print("上传结果：$res");
    } catch (e) {
      print("Upload Image Error: $e");
    }
  }

  Future<void> uploadMultipleImage(List<XFile> files) async {
    try {
      DateTime now = DateTime.now();
      List<Map<String, String>> uploadGroup =
          files
              .map(
                (e) => {
                  "filePath": e.path,
                  "objectKey":
                      "picture/${now.year}/${now.month}/${now.day}/${Uuid().v4()}${now.millisecondsSinceEpoch}.jpg",
                },
              )
              .toList();
      final res = await _flutterHuaweiCloudPlugin.uploadMultipleFile(
        "future-mural",
        uploadGroup,
      );
      print("上传结果：$res");
    } catch (e) {
      print("Upload Image Error: $e");
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('Plugin example app')),
        body: Column(
          children: [
            Text(_filePath),
            ElevatedButton(
              onPressed: pickSingleImage,
              child: const Text("单文件上传"),
            ),
            ElevatedButton(
              onPressed: pickMultipleImage,
              child: const Text("多文件上传"),
            ),
          ],
        ),
      ),
    );
  }
}
